package com.boot.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.boot.entity.*;
import com.boot.mapper.AdDao;
import com.boot.mapper.ConcernDao;
import com.boot.mapper.PushDao;
import com.boot.mapper.UserDao;
import com.boot.paramer.GetAdsParamer;
import com.boot.service.AdService;
import com.boot.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

@Service
public class AdServiceImpl extends ServiceImpl<AdDao, Ad> implements AdService {

	@Resource
	private AdDao addao;
	@Resource
	private UserDao userDao;
	@Resource
	private PushDao pushDao;
	@Resource
	private ConcernDao concernDao;

	@Override
	public AdPushResult save(Ad resad) {
		//System.out.println(ad);
		Ad ad=checkAdDataLength(resad);//判断合法性
		AdPushResult result = new AdPushResult();
		ad.setPull_time(new Timestamp(new Date().getTime()));
		ad.setAd_id(GenerateUniqueId.generateUniqueId());
		ad.setMediatype(0);
		// 判断是否是推送广告
		if (ad.getIspush() == 1) {
			int affectLine = addao.save(ad);
			if (affectLine > 0) {
				//成功之后生成推送记录
				int selectNumber=createPushRecord(ad);
				result.setMsg("发布成功！");
				result.setStatus(1);
				result.setData(ad);
				result.setSelectNumber(selectNumber);
				//修改实际推送出去的数量
				ad.setNumber(selectNumber);
				addao.updateNumber(ad);
			} else {
				result.setMsg("发布失败！");
				result.setStatus(0);
			}
		} else {
			int affectLine = addao.save(ad);
			if (affectLine > 0) {
				result.setMsg("发布成功！");
				result.setStatus(1);
			} else {
				result.setMsg("发布失败！");
				result.setStatus(0);
			}
		}
		return result;
	}
	
	@Override
	public AdPushResult save(Ad resad, HttpServletRequest request, CommonsMultipartFile[] files) {
		//判断合法性
		Ad ad=checkAdDataLength(resad);
		// 定义一个结果对象一共返回
		AdPushResult result = new AdPushResult();
		// 存储当前广告多张图片的组合地址以","隔开（也是写入数据库的地址）
		String filepaths = "";
		// 存储当前广告多张缩略图的组合地址以","隔开（也是写入数据库的地址）
		// String thrumPhotos = "";
		// 获取项目的根目录
		String basePath = request.getSession().getServletContext().getRealPath(File.separator);
		// System.out.println(basePath);
		// 保存相应的图片至对应的文件存储目录
		if (files != null) {
			try {
				for (int i = 0; i < files.length; i++) {
					// 定义当前时间
					Date now = new Date();
					InputStream in = files[i].getInputStream();
					//String relatedpath = "upload" + File.separator + "adphotos" + File.separator + now.getTime()+ files[i].getOriginalFilename();
					String relatedpath = "upload/adphotos/" + now.getTime()+ files[i].getOriginalFilename();
					// 将生成的每一张图片的地址拼到 存储多张图片的字符串的地址中
					if (i == (files.length - 1)) {
						filepaths = filepaths + relatedpath;
					} else {
						filepaths = filepaths + relatedpath + ",";
					}
					File file = new File(basePath + relatedpath);
					FileOutputStream fos = new FileOutputStream(file);
					int len = -1;
					byte[] bytes = new byte[1024];
					while ((len = in.read(bytes)) != -1) {
						fos.write(bytes, 0, len);
					}
					in.close();
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				result.setMsg("失败了");
				result.setStatus(0);
				return result;
			}
		}
		ad.setPull_time(new Timestamp(new Date().getTime()));
		ad.setAd_id(GenerateUniqueId.generateUniqueId());
		ad.setPhotos(filepaths);
		ad.setMediatype(0);
		int resultcode = addao.save(ad);
		if (resultcode > 0) {
			if(ad.getIspush()==1){
				//成功之后生成推送记录
				int selectNumber=createPushRecord(ad);
				result.setData(ad);
				result.setSelectNumber(selectNumber);
			}
			result.setMsg("发布成功！");
			result.setStatus(1);
		} else {
			result.setMsg("发布失败！");
			result.setStatus(0);
		}
		return result;
	}
	
	@Override
	public AdPushResult saveWithVideo(Ad resad, HttpServletRequest request,@RequestParam(value = "files", required = false) CommonsMultipartFile[] files) {
		//判断合法性
		Ad ad=checkAdDataLength(resad);
		// 定义一个结果对象一共返回
		AdPushResult result = new AdPushResult();
		//视频地址
		String videoPath = "";
		//视频缩略图地址
		String posterPath = "";
		// 存储当前广告多张缩略图的组合地址以","隔开（也是写入数据库的地址）
		// String thrumPhotos = "";
		// 获取项目的根目录
		String basePath = request.getSession().getServletContext().getRealPath(File.separator);
		// System.out.println(basePath);
		// 保存相应的图片至对应的文件存储目录
		if (files != null) {
			try {
				for (int i = 0; i < files.length; i++) {
					if(i==0){
						// 定义当前时间
						Date now = new Date();
						InputStream in = files[i].getInputStream();
						//String relatedpath = "upload" + File.separator + "adphotos" + File.separator + now.getTime()+ files[i].getOriginalFilename();
						String relatedpath = "upload/video/" + now.getTime()+ files[i].getOriginalFilename();
						// 将生成的每一张图片的地址拼到 存储多张图片的字符串的地址中
//								if (i == (files.length - 1)) {
							videoPath = videoPath + relatedpath;
//								} else {
//									videoPath = videoPath + relatedpath + ",";
//								}
						File file = new File(basePath + relatedpath);
						FileOutputStream fos = new FileOutputStream(file);
						int len = -1;
						byte[] bytes = new byte[1024];
						while ((len = in.read(bytes)) != -1) {
							fos.write(bytes, 0, len);
						}
						in.close();
						fos.close();
					}
					if(i==1){
						// 定义当前时间
						Date now = new Date();
						InputStream in = files[i].getInputStream();
						//String relatedpath = "upload" + File.separator + "adphotos" + File.separator + now.getTime()+ files[i].getOriginalFilename();
						String relatedpath = "upload/poster/" + now.getTime()+ files[i].getOriginalFilename();
						// 将生成的每一张图片的地址拼到 存储多张图片的字符串的地址中
//								if (i == (files.length - 1)) {
							posterPath = posterPath + relatedpath;
//								} else {
//									posterPath = posterPath + relatedpath + ",";
//								}
						File file = new File(basePath + relatedpath);
						FileOutputStream fos = new FileOutputStream(file);
						int len = -1;
						byte[] bytes = new byte[1024];
						while ((len = in.read(bytes)) != -1) {
							fos.write(bytes, 0, len);
						}
						in.close();
						fos.close();
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
				result.setMsg("失败了");
				result.setStatus(0);
				return result;
			}
		}
		ad.setPull_time(new Timestamp(new Date().getTime()));
		ad.setAd_id(GenerateUniqueId.generateUniqueId());
		ad.setMediatype(1);
		ad.setVideo(videoPath);
		ad.setPoster(posterPath);
		int resultcode = addao.save(ad);
		if (resultcode > 0) {
			if(ad.getIspush()==1){
				//成功之后生成推送记录
				int selectNumber=createPushRecord(ad);
				result.setData(ad);
				result.setSelectNumber(selectNumber);
			}
			result.setMsg("发布成功！");
			result.setStatus(1);
		} else {
			result.setMsg("发布失败！");
			result.setStatus(0);
		}
		return result;
	}

	/**
	 * 生成推送记录
	 * @param ad
	 */
	private int createPushRecord(Ad ad) {
		int selectUserNumbers=0;
		//定位推送
		if (ad.getPushmethod()!=null && ad.getPushmethod().equals("1")) {
			selectUserNumbers = getUsersByLocation(ad);
			//区域推送
		} else {
			selectUserNumbers = getUsersByArea(ad);
		}
		return selectUserNumbers;
	}
	
	/**
	 * 定位推送用户筛选
	 * @param ad
	 */
	private int getUsersByLocation(Ad ad) {
		System.out.println("location:"+ad);
		//广告定位发布的区域中心坐标
		Double lng=ad.getLon();
		Double lat=ad.getLat();
		//定位半径
		Double radius=ad.getRadius();
		if(lng==null && lat==null && radius==null){
			return 0;
		}
		//如果某个限制条件为空则将其设置为-1
		if(ad.getAgestart()==null){
			ad.setAgestart(-1);
		}
		if(ad.getAgeend()==null){
			ad.setAgeend(-1);
		}
		if(ad.getSex()==null){
			ad.setSex("-1");
		}
		if(ad.getJob_id()==null){
			ad.setJob_id("-1");
		}
		//通过年龄性别职业筛选出来的用户
		List<User> users=userDao.getUsersBylocationArg(ad);
		//临时存储符和条件的用户
		List<User> tempUsers=new ArrayList<User>();
		//再根据用户的经纬度进一步筛选用户
		for(int i=0;i<users.size();i++){
			if(users.get(i).getLat()==null || users.get(i).getLon()==null){
				continue;
			}
			double distance=MapUtils.GetDistance(lat,lng,users.get(i).getLat(),users.get(i).getLon());
			if(radius>=distance){
				System.out.println(users.get(i));
				tempUsers.add(users.get(i));
			}
		}
		//通过职业代码筛选用户的条件
		String job_ids=ad.getJob_id();
		//在users的基础上通过职业代码筛选出来的用户
		List<User> usersAfterByJob=new ArrayList<>();
		if(!job_ids.equals("-1")){
			//在此根据job_id筛选用户
			for(int i=0;i<users.size();i++){
				String job_id=users.get(i).getJob_id();
				String job_id_second=users.get(i).getJob_id_second();
				String job_id_third=users.get(i).getJob_id_third();
				System.out.println(job_id+";"+job_id_second);
				if(job_id!=null && job_ids.contains(job_id)){
					usersAfterByJob.add(users.get(i));
					continue;
				}
				if(job_id_second!=null && job_ids.contains(job_id_second)){
					usersAfterByJob.add(users.get(i));
					continue;
				}
				if(job_id_third!=null && job_ids.contains(job_id_third)){
					usersAfterByJob.add(users.get(i));
					continue;
				}
			}
		}else{
			usersAfterByJob=tempUsers;
		}
		//生成为每个用户推送广告的记录
		if(usersAfterByJob.size()>0){
			insertIntoPushTable(usersAfterByJob,ad);
		}
		System.out.println("tempUsers:"+usersAfterByJob);
		return usersAfterByJob.size()>=ad.getNumber()?ad.getNumber():usersAfterByJob.size();
	}

	
	/**
	 * 区域推送用户筛选
	 * @param ad
	 */
	private int getUsersByArea(Ad ad) {
		System.out.println(ad);
		//判断属于那个区域如果那个区域为空则将其值设置成“-1”
		if(ad.getTown()==null){
			ad.setTown("-1");
		}
		if(ad.getDistrict()==null){
			ad.setDistrict("-1");
		}
		if(ad.getCity()==null){
			ad.setCity("-1");
		}
		if(ad.getProvince()==null || ad.getProvince().equals("000000000")){
			ad.setProvince("-1");
		}
		//其他条件如果为空也设置成“-1”
		if(ad.getAgestart()==null){
			ad.setAgestart(-1);
		}
		if(ad.getAgeend()==null){
			ad.setAgeend(-1);
		}
		if(ad.getSex()==null || ad.getSex().equals("")){
			ad.setSex("-1");
		}
		if(ad.getJob_id()==null){
			ad.setJob_id("-1");
		}
		//通过职业代码筛选用户的条件
		String job_ids=ad.getJob_id();
		//通过年龄性别区域筛选出来的用户
		List<User> users=userDao.getUsersByAreaArg(ad);
		//在users的基础上通过职业代码筛选出来的用户
		List<User> usersAfterByJob=new ArrayList<>();
		if(!job_ids.equals("-1")){
			//在此根据job_id筛选用户
			for(int i=0;i<users.size();i++){
				String job_id=users.get(i).getJob_id();
				String job_id_second=users.get(i).getJob_id_second();
				String job_id_third=users.get(i).getJob_id_third();
				System.out.println(job_id+";"+job_id_second);
				if(job_id!=null && job_ids.contains(job_id)){
					usersAfterByJob.add(users.get(i));
					continue;
				}
				if(job_id_second!=null && job_ids.contains(job_id_second)){
					usersAfterByJob.add(users.get(i));
					continue;
				}
				if(job_id_third!=null && job_ids.contains(job_id_third)){
					usersAfterByJob.add(users.get(i));
					continue;
				}
			}
		}else{
			usersAfterByJob=users;
		}
		//生成为每个用户推送广告的记录
		if(usersAfterByJob.size()>0){
			insertIntoPushTable(usersAfterByJob,ad);
		}
		System.out.println("users:"+usersAfterByJob);
		return usersAfterByJob.size()>=ad.getNumber()?ad.getNumber():usersAfterByJob.size();
	}
	
	/**
	 * 通过一个线程生成推送记录
	 * @param users
	 * @param ad
	 */
	private void insertIntoPushTable(final List<User> users,final Ad ad) {
		Runnable runnable=new Runnable() {
			@Override
			public void run() {
				Push push=null;
				Date date=new Date();
				int number=users.size()>=ad.getNumber()?ad.getNumber():users.size();
				for(int i=0;i<number;i++){
					push=new Push();
					push.setAccept(0);
					push.setAd_id(ad.getAd_id());
					push.setPrice(ad.getPrice());
					push.setUser_id(ad.getUser_id());
					push.setUsername(users.get(i).getUsername());
					if(users.get(i).getDevicetype()!=null && !users.get(i).getDevicetype().equals("")){
						push.setDevicetype(users.get(i).getDevicetype());
					}
					push.setTime(date);
					push.setUser_accept_id(users.get(i).getUser_id());
					pushDao.save(push);
					//将用户未读数量加1
					userDao.plusUnReadAds(users.get(i).getUser_id());
				}
			}
		};
		Thread t=new Thread(runnable);
		t.start();
	}

	

	@Override
	public AdResult getAds(GetAdsParamer paramer) {
		//System.out.println(paramer);
		String province = paramer.getProvinceCode()==null?"-1":paramer.getProvinceCode();
		String city = paramer.getCityCode()==null?"-1":paramer.getCityCode();
		String district = paramer.getDistrictCode()==null?"-1":paramer.getDistrictCode();
		String town = paramer.getTownCode()==null?"-1":paramer.getTownCode();
		AdResult result = new AdResult();
		List<Ad> ads = null;
		// 定义一个map用于存储用户的请求参数
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("pageIndex", (paramer.getPageIndex() - 1) * paramer.getPageSize());
		params.put("pageSize", paramer.getPageSize());
		params.put("type", paramer.getType());
		params.put("secondtype", paramer.getSecondtype());
		params.put("province", province);
		params.put("city", city);
		params.put("district", district);
		params.put("town", town);
		// System.out.println("请求参数"+paramer);
		if (paramer.getMethod()!=null && paramer.getMethod().equals(ConstantValue.ISLOCATION)) {
			// 手机自动获取经纬度进行定位
			params.put("country", "000000000");
			if (paramer.getType() == 1) {
				System.out.println("params"+params);
				ads = addao.getAdsAuto(params);
			} else {
				ads = addao.getAdsAutoType(params);
			}
		} else if (paramer.getType() == 1) {
			if (province.equals("-1") && city.equals("-1") && district.equals("-1") && town.equals("-1")) {
				// 国家级
				// System.out.println(params);
				ads = addao.getAdsByCountry(params);
			} else if (city.equals("-1") && district.equals("-1") && town.equals("-1")) {
				// 省级获取广告
				ads = addao.getAdsByProvince(params);
			} else if (district.equals("-1") && town.equals("-1")) {
				// 市级获取广告
				ads = addao.getAdsByCity(params);
			} else if (town.equals("-1")) {
				// 县级获取广告
				ads = addao.getAdsByDistrict(params);
			} else {
				// 镇级获取广告
				ads = addao.getAdsByTown(params);
			}
		} else {
			if (province.equals("-1") && city.equals("-1") && district.equals("-1") && town.equals("-1")) {
				// 国家级
				ads = addao.getAdsByCountryType(params);
			} else if (city.equals("-1") && district.equals("-1") && town.equals("-1")) {
				// 省级获取广告
				ads = addao.getAdsByProvinceType(params);
			} else if (district.equals("-1") && town.equals("-1")) {
				// 市级获取广告
				ads = addao.getAdsByCityType(params);
			} else if (town.equals("-1")) {
				// 县级获取广告
				ads = addao.getAdsByDistrictType(params);
			} else {
				// 镇级获取广告
				ads = addao.getAdsByTownType(params);
			}
		}
		if (ads != null) {
			result.setStatus(1);
			result.setMsg("获取成功");
			result.setData(ads);
		} else {
			result.setStatus(0);
			result.setMsg("获取失败");
		}
		return result;
	}
	
	@Override
	public AdResult getAdsIos(GetAdsParamer paramer) {
		AdAreaResult adAreaResult=new AdAreaResult();
		List<Area> areas=new ArrayList<>();
		//根据定位获取的省市县名称获取对应的行政代码
		Map<String,String> map=new HashMap<>();
		map.put("province", paramer.getProvinceCode());
		map.put("city", paramer.getCityCode());
		map.put("district", paramer.getDistrictCode());
		Area provinceArea=addao.getAreasByProvinceName(map);
		if(provinceArea!=null){
			areas.add(provinceArea);
			map.put("provinceCode", provinceArea.getAreacode());
		}else{
			map.put("provinceCode", "-1");
		}
		Area cityArea=addao.getAreaByCityName(map);
		if(cityArea!=null){
			areas.add(cityArea);
			map.put("cityCode", cityArea.getAreacode());
		}else{
			map.put("cityCode", "-1");
		}
		Area districtArea=addao.getAreaByDistrictName(map);
		if(districtArea!=null){
			areas.add(districtArea);
			map.put("districtCode", districtArea.getAreacode());
		}else{
			map.put("districtCode", "-1");
		}
		adAreaResult.setArea(areas);
		paramer.setProvinceCode(map.get("provinceCode"));
		paramer.setCityCode(map.get("cityCode"));
		paramer.setDistrictCode(map.get("districtCode"));
		
		String province = paramer.getProvinceCode();
		String city = paramer.getCityCode();
		String district = paramer.getDistrictCode();
		String town = paramer.getTownCode();
		List<Ad> ads = null;
		// 定义一个map用于存储用户的请求参数
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("pageIndex", (paramer.getPageIndex() - 1) * paramer.getPageSize());
		params.put("pageSize", paramer.getPageSize());
		params.put("type", paramer.getType());
		params.put("secondtype", paramer.getSecondtype());
		params.put("province", paramer.getProvinceCode());
		params.put("city", paramer.getCityCode());
		params.put("district", paramer.getDistrictCode());
		params.put("town", paramer.getTownCode());
		// System.out.println("请求参数"+paramer);
		if (paramer.getMethod()!=null && paramer.getMethod().equals(ConstantValue.ISLOCATION)) {
			// 手机自动获取经纬度进行定位
			params.put("country", "000000000");
			if (paramer.getType() == 1) {
				System.out.println("params"+params);
				ads = addao.getAdsAuto(params);
			} else {
				ads = addao.getAdsAutoType(params);
			}
		} else if (paramer.getType() == 1) {
			if (province.equals("-1") && city.equals("-1") && district.equals("-1") && town.equals("-1")) {
				// 国家级
				// System.out.println(params);
				ads = addao.getAdsByCountry(params);
			} else if (city.equals("-1") && district.equals("-1") && town.equals("-1")) {
				// 省级获取广告
				ads = addao.getAdsByProvince(params);
			} else if (district.equals("-1") && town.equals("-1")) {
				// 市级获取广告
				ads = addao.getAdsByCity(params);
			} else if (town.equals("-1")) {
				// 县级获取广告
				ads = addao.getAdsByDistrict(params);
			} else {
				// 镇级获取广告
				ads = addao.getAdsByTown(params);
			}
		} else {
			if (province.equals("-1") && city.equals("-1") && district.equals("-1") && town.equals("-1")) {
				// 国家级
				ads = addao.getAdsByCountryType(params);
			} else if (city.equals("-1") && district.equals("-1") && town.equals("-1")) {
				// 省级获取广告
				ads = addao.getAdsByProvinceType(params);
			} else if (district.equals("-1") && town.equals("-1")) {
				// 市级获取广告
				ads = addao.getAdsByCityType(params);
			} else if (town.equals("-1")) {
				// 县级获取广告
				ads = addao.getAdsByDistrictType(params);
			} else {
				// 镇级获取广告
				ads = addao.getAdsByTownType(params);
			}
		}
		if (ads != null) {
			adAreaResult.setStatus(1);
			adAreaResult.setMsg("获取成功");
			adAreaResult.setData(ads);
		} else {
			adAreaResult.setStatus(0);
			adAreaResult.setMsg("获取失败");
		}
		return adAreaResult;
	}

	@Override
	public AdResult getAdsByKeyword(GetAdsParamer paramer) {
		String province = paramer.getProvinceCode()==null?"-1":paramer.getProvinceCode();
		String city = paramer.getCityCode()==null?"-1":paramer.getCityCode();
		String district = paramer.getDistrictCode()==null?"-1":paramer.getDistrictCode();
		String town = paramer.getTownCode()==null?"-1":paramer.getTownCode();
		AdResult result = new AdResult();
		List<Ad> ads;
		// 定义一个map用于存储用户的请求参数
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("pageIndex", (paramer.getPageIndex() - 1) * paramer.getPageSize());
		params.put("pageSize", paramer.getPageSize());
		params.put("type", paramer.getType());
		params.put("secondtype", paramer.getSecondtype());
		params.put("province", province);
		params.put("city", city);
		params.put("district", district); 
		params.put("town", town);
		params.put("keyword", paramer.getKeyword());
		 System.out.println(params);
		// 获取列表并返回结果
		if (province.equals("-1") && city.equals("-1") && district.equals("-1") && town.equals("-1")) {
			// 国家级
			ads = addao.getCountryAdsByKeyword(params);
		} else if (city.equals("-1") && district.equals("-1") && town.equals("-1")) {
			// 省级获取广告
			ads = addao.getProvinceAdsByKeyword(params);
		} else if (district.equals("-1") && town.equals("-1")) {
			// 市级获取广告
			ads = addao.getCityAdsByKeyword(params);
		} else if (town.equals("-1")) {
			// 县级获取广告
			ads = addao.getDistrictAdsByKeyword(params);
		} else {
			// 镇级获取广告
			ads = addao.getTownAdsByKeyword(params);
		}
		if (ads != null) {
			result.setStatus(1);
			result.setMsg("获取成功");
			result.setData(ads);
		} else {
			result.setStatus(0);
			result.setMsg("获取失败");
		}
		return result;
	}

	@Override
	public AdResult getAdById(String ad_id) {
		AdResult result = new AdResult();
		// 获取某条广告
		Ad ad = addao.getAdById(ad_id);
		addao.increaseAdClicks(ad_id);
		if (ad != null) {
			result.setStatus(1);
			result.setMsg("获取成功");
			result.setData(ad);
		} else {
			result.setStatus(0);
			result.setMsg("获取失败");
		}
		return result;
	}

	@Override
	public AdResult recordScan(int ad_id, int clicks) {
		AdResult result = new AdResult();
		HashMap<String, Integer> params = new HashMap<String, Integer>();
		params.put("ad_id", ad_id);
		params.put("clicks", clicks);
		int i = addao.recordScan(params);
		if (i > 0) {
			result.setMsg("记录成功");
			result.setStatus(1);
		} else {
			result.setMsg("记录失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) // 开启事务
	public AdResult getAdAndUserInfo(String ad_id) {
		AdResult result = new AdResult();
		// 获取某条广告
		Ad ad = addao.getAdInfo(ad_id);
		//点击量增加1
		addao.increaseAdClicks(ad_id);
		//System.out.println("id=" + ad_id);
		if (ad != null) {
			List<Comment> comments = addao.getCommentsByAdId(ad_id);
			if (comments != null) {
				ad.setComments(comments);
			}
			// System.out.println("手机号:" + ad.getUser().getPhone());
			result.setStatus(1);
			result.setMsg("获取成功");
			result.setData(ad);
		} else {
			result.setStatus(0);
			result.setMsg("获取失败");
		}
		return result;
	}
	@Transactional
	@Override
	public AdResult publishAdComment(Comment comment) {
		AdResult result = new AdResult();
		// 发布一条评论,返回结果码
		// 设置评论发布时间
		comment.setAddtime(new Date());
		comment.setIsAddGood(0);
		comment.setComment_id(GenerateUniqueId.generateUniqueId());
		comment.setContent(StringUtil.subString(comment.getContent(), 240));
		int resultcode = addao.publishAdComment(comment);
		addao.increateCommentNumber(comment.getAd_id());
		if (resultcode > 0) {// 表示插入数据库成功
			List<Comment> comments=new ArrayList<>();
			comments.add(comment);
			result.setStatus(1);
			result.setMsg("发布成功");
			result.setData(comments);
		} else {// 失败
			result.setStatus(0);
			result.setMsg("发布失败");
		}
		return result;
	}

	@Override
	public AdResult getCommentsByAdId(String adid) {
		AdResult result = new AdResult();
		// 用于存储评论实例
		List<Comment> comments = new ArrayList<Comment>();
		// 获取所有评论
		comments = addao.getCommentsByAdId(adid);
		if (comments != null) {// 表示评论至少有一条
			result.setData(comments);
			result.setMsg("获取评论成功");
			result.setStatus(1);
		} else {
			result.setMsg("获取评论失败");
			result.setStatus(0);
		}
		return result;
	}
	@Transactional
	@Override
	public AdResult publishAdCommentReply(CommentReply commentReply) {
		AdResult result = new AdResult();
		// 发布一条评论的回复,返回结果码
		// 设置评论发布时间
		commentReply.setAddtime(new Date());
		commentReply.setComment_reply_id(GenerateUniqueId.generateUniqueId());
		commentReply.setContent(StringUtil.subString(commentReply.getContent(), 240));
		int resultcode = addao.publishAdCommentReply(commentReply);
        //修改回复数量
		addao.updateAdCommentNumber(commentReply.getComment_id());
		if (resultcode > 0) {// 表示插入数据库成功
			List<CommentReply> comments=new ArrayList<>();
			comments.add(commentReply);
			result.setData(comments);
			result.setStatus(1);
			result.setMsg("发布成功");
		} else {// 失败
			result.setStatus(0);
			result.setMsg("发布失败");
		}
		return result;
	}

//	@Override
//	public AdResult updateAdCommentNumber(String comment_id) {
//		AdResult result = new AdResult();
//		int resultcode = addao.updateAdCommentNumber(comment_id);
//		if (resultcode > 0) {
//			result.setStatus(1);
//			result.setMsg("发布成功");
//		} else {
//			result.setStatus(0);
//			result.setMsg("发布失败");
//		}
//		return result;
//
//	}

	@Override
	public AdResult getCommentReplys(String user_id,String comment_id,Integer pageIndex,Integer pageSize) {
		AdResult result = new AdResult();
		Map<String,Object> params=new HashMap<>();
		params.put("comment_id", comment_id);
		params.put("pageIndex", (pageIndex-1)*pageSize);
		params.put("pageSize", pageSize);
		// 获取某条评论的回复
		List<CommentReply> commentreplys = addao.getCommentReplys(params);
		if (commentreplys != null) {
			Addgood paramgood=new Addgood();
		    for(int i=0;i<commentreplys.size();i++){
		    	paramgood.setComment_id(commentreplys.get(i).getComment_reply_id());
		    	paramgood.setUser_id(user_id);
		    	Addgood resultgood=addao.getAddgoodByCommentAndUserId(paramgood);
		    	if(resultgood!=null){
		    		commentreplys.get(i).setIsAddGood(1);
		    	}
		    }
			result.setData(commentreplys);
			result.setMsg("获取评论回复成功");
			result.setStatus(1);
		} else {
			result.setMsg("获取评论回复失败");
			result.setStatus(0);
		}
		return result;
	}

	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) // 开启事务
	public AdResult deleteCommentById(String ad_id,String comment_id) {
		AdResult result = new AdResult();
		//删除当前评论
		int resultcode = addao.deleteCommentById(comment_id);
		addao.reduceCommentNumber(ad_id);
		if(resultcode>0){
			//删除对此评论的回复
			addao.deleteReplys(comment_id);
			result.setMsg("删除成功");
			result.setStatus(1);
		}else{
			result.setMsg("删除失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult doPayByBalance(String ad_id,String pay_password,String token) {
		AdResult adResult=new AdResult();
		//获取广告信息
		Ad ad=addao.getAdById(ad_id);
		//判断是否已经支付
		if(ad.getIspayed()!=null){
			int isPayed=ad.getIspayed();
			if(isPayed==1){
				adResult.setMsg("已经支付");
				adResult.setStatus(5);
				return adResult;
			}
		}
		//System.out.println(ad);
		double total=ad.getNumber()*ad.getPrice().doubleValue();
		User user=new User();
		//判断用户的余额是否足够
		HashMap<String, String> map=new HashMap<>();
		map.put("user_id",ad.getUser_id());
		map.put("token",token);
		User user2=userDao.getUserInfo(map);
		//校验是否被冻结
		Date now=new Date();
		if(user2!=null){
			Date lock_pay_time=user2.getPay_lock_time();
			if(lock_pay_time!=null && now.getTime()-lock_pay_time.getTime()<24*60*60*1000){
				adResult.setMsg("您的账号已被锁定");
				adResult.setStatus(4);
				return adResult;
			}
		}
		//System.out.println(EncodeUtil.md5(pay_password)+":"+user2.getPay_password());
		//校验支付密码
		if(!EncodeUtil.md5(pay_password).equals(user2.getPay_password())){
			adResult.setMsg("支付密码错误");
			adResult.setStatus(3);
			return adResult;
		}
		if(user2.getBalance()==null || total>Double.parseDouble(user2.getBalance().toString())){
			adResult.setMsg("余额不足");
			adResult.setStatus(2);
			return adResult;
		}
		user.setUser_id(ad.getUser_id());
		user.setBalance(new BigDecimal(total));
		int lines=userDao.doPayByBalance(user);
		if(lines>0){
			//修改广告的审核状态为0
			addao.makeAdNeedCheck(ad_id);
			adResult.setMsg("支付成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("支付失败");
			adResult.setStatus(0);
		}
		return adResult;
	}

	

	@Override
	public AdCommentsResult getComments(String ad_id,String user_id,String store_id,Integer pageIndex, Integer pageSize) {
		AdCommentsResult adResult=new AdCommentsResult();
		Map<String,Object> params=new HashMap<>();
		params.put("ad_id", ad_id);
		params.put("pageIndex", (pageIndex-1)*pageSize);
		params.put("pageSize", pageSize);
	    List<Comment> comments=addao.getComments(params);
	    if(user_id!=null && !user_id.equals("")){
	    	Concern concern=new Concern();
		    concern.setStore_id(store_id);
		    concern.setUser_id(user_id);
		    Concern concernGeted=concernDao.getConcern(concern);
		    if(concernGeted!=null){
		    	adResult.setIsConcerned(1);
		    }else{
		    	adResult.setIsConcerned(0);
		    }
		    CollectionAd collection=new CollectionAd();
		    collection.setAd_id(ad_id);
		    collection.setUser_id(user_id);
		    CollectionAd collectionResult=addao.getCollection(collection);
		    if(collectionResult!=null){
		    	adResult.setIsCollected(1);
		    }else{
		    	adResult.setIsCollected(0);
		    }
	    }else{
	    	adResult.setIsCollected(0);
	    	adResult.setIsConcerned(0);
	    }
	    Addgood paramgood=new Addgood();
	    for(int i=0;i<comments.size();i++){
	    	paramgood.setComment_id(comments.get(i).getComment_id());
	    	paramgood.setUser_id(user_id);
	    	Addgood resultgood=addao.getAddgoodByCommentAndUserId(paramgood);
	    	if(resultgood!=null){
	    		comments.get(i).setIsAddGood(1);
	    	}
	    }
	    if(comments!=null && comments.size()>0){
	    	adResult.setData(comments);
	    	adResult.setMsg("成功获取到了评论");
	    	adResult.setStatus(1);
	    }else{
	    	adResult.setMsg("未获取到了评论");
	    	adResult.setStatus(0);
	    }
		return adResult;
	}

	@Transactional
	@Override
	public AdResult deleteAdCommentReply(String comment_id,String comment_reply_id) {
		AdResult adResult=new AdResult();
		int affect_line=addao.deleteCommentReply(comment_reply_id);
		addao.reduceAdCommentNumber(comment_id);
		if(affect_line>0){
			adResult.setMsg("删除成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("删除失败");
			adResult.setStatus(0);
		}
		return adResult;
	}
	
	@Transactional
	@Override
	public AdResult addGood(String comment_id, String user_id) {
		AdResult adResult=new AdResult();
		//先获取点赞实例，再修改点赞的数量
		Addgood paramgood=new Addgood();
		paramgood.setComment_id(comment_id);
		paramgood.setUser_id(user_id);
		Addgood addgood=addao.getAddgoodByCommentAndUserId(paramgood);
		//已经点过赞
		if(addgood!=null){
			//减少点赞数量
			addao.reduceCommentGoodnumber(comment_id);
			//移除点赞实例
			Addgood good=new Addgood();
			good.setComment_id(comment_id);
			good.setUser_id(user_id);
			addao.removeAddgood(good);
			adResult.setMsg("点赞取消");
			adResult.setStatus(2);
		}else{
			//此用户对当前的评论还未进行点赞操作，进行点赞操作
			int affect_line=addao.plusCommentGoodnumber(comment_id);
			if(affect_line>0){
				adResult.setMsg("点赞成功");
				adResult.setStatus(1);
				Addgood good=new Addgood();
				good.setComment_id(comment_id);
				good.setUser_id(user_id);
				good.setCreated_time(new Date());
				addao.addAddgood(good);
			}else{
				adResult.setMsg("点赞失败");
				adResult.setStatus(0);
			}
		}
		return adResult;
	}
    @Transactional
	@Override
	public AdResult collectAdService(CollectionAd collection) {
		AdResult adResult=new AdResult();
		//先查看是否已经收藏了
		CollectionAd collectionGeted=addao.getCollection(collection);
		if(collectionGeted!=null){
			int delete_result=addao.deleteCollection(collection);
			if(delete_result>0){
				adResult.setMsg("取消收藏");
				adResult.setStatus(2);
			}else{
				adResult.setMsg("操作失败");
				adResult.setStatus(0);
			}
		}else{
			collection.setTime(new Date());
			int collect_result=addao.collectAdDao(collection);
			if(collect_result>0){
				adResult.setMsg("收藏成功");
				adResult.setStatus(1);
			}else{
				adResult.setMsg("收藏 失败");
				adResult.setStatus(0);
			}
		}
		return adResult;
	}

	@Override
	public AdResult addReplyGood(String comment_reply_id, String user_id) {
		AdResult adResult=new AdResult();
		//先获取点赞实例，再修改点赞的数量
		Addgood paramgood=new Addgood();
		paramgood.setComment_id(comment_reply_id);
		paramgood.setUser_id(user_id);
		Addgood addgood=addao.getAddgoodByCommentAndUserId(paramgood);
		//已经点过赞
		if(addgood!=null){
			//减少点赞数量
			addao.reduceCommentReplyGoodnumber(comment_reply_id);
			//移除点赞实例
			Addgood good=new Addgood();
			good.setComment_id(comment_reply_id);
			good.setUser_id(user_id);
			addao.removeAddgood(good);
			adResult.setMsg("点赞取消");
			adResult.setStatus(2);
		}else{
			//此用户对当前的评论还未进行点赞操作，进行点赞操作
			int affect_line=addao.plusCommentReplyGoodnumber(comment_reply_id);
			if(affect_line>0){
				adResult.setMsg("点赞成功");
				adResult.setStatus(1);
				Addgood good=new Addgood();
				good.setComment_id(comment_reply_id);
				good.setUser_id(user_id);
				good.setCreated_time(new Date());
				addao.addAddgood(good);
			}else{
				adResult.setMsg("点赞失败");
				adResult.setStatus(0);
			}
		}
		return adResult;
	}

	@Override
	public AdResult addReportService(Report report) {
		AdResult adResult = new AdResult();
		//先判断之前举报过本条评论吗 
		Report paramReport=new Report();
		paramReport.setComment_id(report.getComment_id());
		paramReport.setUser_id(report.getUser_id());
		Report reportGeted=addao.getReport(paramReport);
		if(reportGeted!=null){
			adResult.setMsg("已经举报过了");
			adResult.setStatus(2);
		}else{
			report.setReason(StringUtil.subString(report.getReason(), 100));
			report.setAdd_time(new Date());
			int report_line=addao.addReport(report);
			if(report_line>0){
				adResult.setMsg("举报成功");
				adResult.setStatus(1);
			}else{
				adResult.setMsg("操作失败");
				adResult.setStatus(0);
			}
		}
		return adResult;
	}

	//检查发布数据的字段长度
	public static Ad checkAdDataLength(Ad ad){
		String title=ad.getTitle();
		String content=ad.getContent();
		String tel=ad.getTel();
		String address=ad.getAddress();
		//标题处理
		if(title!=null && title.length()>50){
			ad.setTitle(title.substring(0, 50));
		}
		//内容处理
		if(content!=null && content.length()>1000){
			ad.setContent(content.substring(0,1000));
		}
		//电话号码处理
		if(tel!=null && tel.length()>11){
			ad.setTel(tel.substring(0, 11));
		}
		//地址处理
		if(address!=null && address.length()>64){
			ad.setAddress(address.substring(0, 64));
		}
		return ad;
	}
	

}
